# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2019/8/19 14:15
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
from django.template.loader import render_to_string
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, DeleteView
from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from django.urls import reverse_lazy  # 使用lazy可以在url空符位加载前使用

from web_ask.news.models import News
from web_ask.helpers import ajax_required, AuthorRequireMixin


class NewsListView(LoginRequiredMixin, ListView):
    """首页动态"""
    model = News
    # queryset = News.objects.all()
    paginate_by = 20  # 分页 url自带?page=
    # page_kwarg = 'p'  # 分页查询参数别名
    # context_object_name = 'news_list'  # 查询集在模板视图中的别名，默认是模型类名_list
    # ordering = 'created_at'  # 排序字段，多字段时('x','y') 使用元组， 也可以在model中实现
    template_name = 'news/news_list.html'  # 如果不写会自动关联到，模型类名_list.html

    def get_ordering(self):
        """自定义排序，重构复杂排序，例如热度推荐等"""
        pass

    def get_paginate_by(self, queryset):
        """自定义分页"""
        pass

    def get_queryset(self):
        """返回查询集"""
        return News.objects.filter(reply=False).select_related('user', 'parent').prefetch_related("liked")

    # def get_context_data(self, *, object_list=None, **kwargs):
    #     """添加额外的上下文；添加前端显示的额外信息"""
    #     context = super().get_context_data()
    #     context['views'] = 100
    #     return context


class NewsDeleteView(AuthorRequireMixin, LoginRequiredMixin, DeleteView):
    """AuthorRequireMixin helps 中验证所属权限"""
    model = News
    template_name = 'news/news_confirm_delete.html'
    slug_url_kwarg = 'slug'  # 通过url传入要删除的对象主键id， 默认值是slug
    pk_url_kwarg = 'pk'  # 通过url传入要删除的对象主键id， 默认值是pk
    success_url = reverse_lazy("news:list")  # 在项目URLConf 未加载前使用


@login_required
@ajax_required
@require_http_methods(["POST"])
# POST 大写！！！
def post_new(request):
    """发送动态， AJAX POST请求"""
    post = request.POST['post'].strip()
    if post:
        posted = News.objects.create(user=request.user, content=post)
        html = render_to_string('news/news_single.html', {'news': posted, 'request': request})
        return HttpResponse(html)
    else:
        return HttpResponseBadRequest("内容不能为空")


@login_required
@ajax_required
@require_http_methods(["POST"])
def like(request):
    """点赞， AJAX POST请求"""
    news_id = request.POST['news']
    # 不是get(pk=news_id).select_related('user')因为get获取的是一个数据而不是查询集
    news = News.objects.select_related('user').get(pk=news_id)
    # 取消或者添加赞
    news.switch_like(request.user)
    # 返回赞的数量
    return JsonResponse({'likes': news.count_likers()})


@login_required
@ajax_required
@require_http_methods(["GET"])
def get_thread(request):
    """返回动态的评论， AJAX GET请求"""
    news_id = request.GET['news']
    news = News.objects.filter(pk=news_id).first()
    news_html = render_to_string('news/news_single.html', {'news': news})  # 没有评论时
    # 有评论时
    thread_html = render_to_string('news/news_thread.html', {'thread': news.get_thread(), "current_user": request.user})
    # print(request.user.username)
    return JsonResponse({
        "uuid": news_id,
        "news": news_html,
        "thread": thread_html,
    })


@login_required
@ajax_required
@require_http_methods(["POST"])
def post_comment(request):
    """评论， AJAX POST请求"""
    post = request.POST['reply'].strip()
    parent_id = request.POST['parent']
    parent = News.objects.filter(pk=parent_id).first()
    if post:
        parent.reply_this(request.user, post)
        return JsonResponse({'comments': parent.comment_count()})
    else:
        return HttpResponseBadRequest("内容不能为空")


@login_required
@ajax_required
@require_http_methods(["POST"])
def update_interactions(request):
    """更新互动信息"""
    data_point = request.POST["id_value"]
    news = News.objects.get(pk=data_point)
    return JsonResponse({"likes": news.count_likers(), "comments":news.comment_count()})
